import { request } from "@tarojs/taro";
import { baseURL, paths } from "./config";
import errorCode from "./errorCode";
import { sg, api } from "@utils/index";
import { HttpsApi, RequestOptions, ResponseData } from "types/utils/axios";

export const axios = {
  request: <T = any>(options: RequestOptions): Promise<ResponseData<T>> => {
    return new Promise((resolve, reject) => {
      const startTime = Date.now();
      const token = sg.getValue("token") || "";
      const isAddToken =
        options.url?.includes(paths.weappLoginUrl) ||
        options.url?.includes(paths.codeLoginUrl);
      if (token && !isAddToken) {
        options.header = {
          ...options.header,
          Authorization: `Bearer ${token}`,
        };
      }

      request({
        ...options,
        success: (res) => {
          const endTime = Date.now();
          console.log(`=====================start=======================`);
          console.log(`请求耗时:`, `${(endTime - startTime) / 1000}s`);
          console.log(`请求地址:`, options.url);
          console.log(`请求参数:`, options.data);
          console.log(`响应结果1:`, res?.data);
          console.log(`响应结果2:`, res?.data?.data);
          console.log(`======================end========================\n`);
          // 未设置状态码则默认成功状态
          const code = res.data.code || 200;
          // 获取错误信息
          const msg = errorCode[code] || res.data.msg || errorCode["default"];
          console.log(`请求状态码:`, code);
          if (code === 401) {
            console.error(msg);
            api._toast({ title: msg });
          } else if (code === 500) {
            console.error(msg);
            api._toast({ title: msg });
            reject(new Error(msg));
          } else if (code !== 200) {
            console.error(msg);
            api._toast({ title: msg });
            reject(new Error("error"));
          } else {
            // 缓存token
            if (res?.data?.token) {
              sg.set("token", res.data.token, 60 * 30 * 1000); // 保存token到本地缓存，有效期30分钟
            }
            // 缓存用户信息
            if (options?.url?.includes(paths.getUserInfoUrl)) {
              sg.set("userInfo", res.data.data, 60 * 30 * 1000); // 保存用户信息到本地缓存，有效期30分钟
            }
            resolve(res as ResponseData<T>);
          }
        },
        fail: reject,
      });
    });
  },
  get: <T = any, D = any>(
    url: string,
    params?: D
  ): Promise<ResponseData<T>> => {
    return axios.request({
      url,
      method: "GET",
      data: params,
    });
  },
  post: <T = any, D = any>(url: string, data?: D): Promise<ResponseData<T>> => {
    return axios.request({
      url,
      method: "POST",
      data,
    });
  },
};

const httpsApi: HttpsApi = {};
for (const key in paths) {
  httpsApi[key.replace("Url", "")] = <T = any, D = any>(
    data?: D
  ): Promise<ResponseData<T>> => {
    return axios.post(`${baseURL}${paths[key]}`, data);
  };
}
export const https = httpsApi;
